package com.xxl.job.admin.core.scheduler;

import com.xxl.job.admin.core.conf.XxlJobAdminConfig;
import com.xxl.job.admin.core.thread.*;
import com.xxl.job.admin.core.util.I18nUtil;
import com.xxl.job.core.biz.ExecutorBiz;
import com.xxl.job.core.biz.client.ExecutorBizClient;
import com.xxl.job.core.enums.ExecutorBlockStrategyEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author xuxueli 2018-10-28 00:18:17
 */

public class XxlJobScheduler  {
    private static final Logger logger = LoggerFactory.getLogger(XxlJobScheduler.class);


    public void init() throws Exception {
        // 初始化语言配置（application.properties中的xxl.job.i18n）
        initI18n();

        // 初始化两个线程池，快触发线程池和慢触发线程池，快触发线程池队列1000，慢触发2000，核心线程数均10
        JobTriggerPoolHelper.toStart();

        /**
         * 启动注册监控器（将注册到register表中的IP加载到group表）/ 30执行一次
         * 保证任务执行时拿到的执行器列表都是运行的
         * 每30s查询数据库中自动注册的所有执行器
         * 查询90s未再次注册的执行器，并删除其register表
         * update更新90秒内活跃的group执行器表的addressList
         *
         * 1、每30心跳时间执行一次，通过http请求向执行器netty发送请求检测请求，返回success就更新执行器表中updateTime
         * 2、并且移除表中90秒内未更新的执行器
         */
        JobRegistryHelper.getInstance().start();

        // 任务失败重试，每10s执行一次
        JobFailMonitorHelper.getInstance().start();

        // 任务结果丢失处理：调度记录停留在 "运行中" 状态超过10min，且对应执行器心跳注册失败不在线，则将本地调度主动标记失败；
        JobCompleteHelper.getInstance().start();

        // 1、日志归总，3天内执行成功、失败、运行中的日志数量，2、清除数据库日志
        JobLogReportHelper.getInstance().start();

        // 启动定时任务调度器（执行任务，缓存任务）
        JobScheduleHelper.getInstance().start();

        logger.info(">>>>>>>>> init xxl-job admin success.");
    }

    
    public void destroy() throws Exception {

        // stop-schedule
        JobScheduleHelper.getInstance().toStop();

        // admin log report stop
        JobLogReportHelper.getInstance().toStop();

        // admin lose-monitor stop
        JobCompleteHelper.getInstance().toStop();

        // admin fail-monitor stop
        JobFailMonitorHelper.getInstance().toStop();

        // admin registry stop
        JobRegistryHelper.getInstance().toStop();

        // admin trigger pool stop
        JobTriggerPoolHelper.toStop();

    }

    // ---------------------- I18n ----------------------

    private void initI18n(){
        for (ExecutorBlockStrategyEnum item:ExecutorBlockStrategyEnum.values()) {
            item.setTitle(I18nUtil.getString("jobconf_block_".concat(item.name())));
        }
    }

    // ---------------------- executor-client ----------------------
    private static ConcurrentMap<String, ExecutorBiz> executorBizRepository = new ConcurrentHashMap<String, ExecutorBiz>();
    public static ExecutorBiz getExecutorBiz(String address) throws Exception {
        // valid
        if (address==null || address.trim().length()==0) {
            return null;
        }

        // load-cache
        address = address.trim();
        ExecutorBiz executorBiz = executorBizRepository.get(address);
        if (executorBiz != null) {
            return executorBiz;
        }

        // set-cache
        executorBiz = new ExecutorBizClient(address, XxlJobAdminConfig.getAdminConfig().getAccessToken());

        executorBizRepository.put(address, executorBiz);
        return executorBiz;
    }

}
